package Win;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example9_14 {
   public static void main(String args[]) {
     WindowButton win=new WindowButton("猜数字");
   }
}
class WindowButton extends JFrame implements ActionListener {
   int number;
   JLabel hintLabel,Time,check; 
   JTextField inputGuess;
   JButton buttonGetNumber,buttonEnter;
   //Timer time;
    
   WindowButton(String s) {
      super(s);
      addWindowListener( new WindowAdapter(){ //匿名类的实例监视窗口事件
                            public void windowClosing(WindowEvent e) {
                                dispose();
                            }
                         } 
                       );  
     //time=new Timer(3000,this);
      setLayout(new FlowLayout());
      buttonGetNumber=new JButton("得到一个随机数");
      add(buttonGetNumber);
      hintLabel=new JLabel("输入你的猜测：",JLabel.CENTER);
      check=new JLabel("判断输赢：",JLabel.CENTER);
      add(check);
      Time=new JLabel("时间：");
      hintLabel.setBackground(Color.cyan);
      inputGuess=new JTextField("0",10); 
      add(hintLabel);
      add(Time,BorderLayout.CENTER);
      add(inputGuess);
      buttonEnter=new JButton("确定"); 
      add(buttonEnter); 
      buttonEnter.addActionListener(this);
      buttonGetNumber.addActionListener(this);
      setBounds(500,500,500,500);
      setVisible(true);
      validate();
    }
   long startTime = System.currentTimeMillis();
    public void actionPerformed(ActionEvent e) {
         if(e.getSource()==buttonGetNumber) {
            number=(int)(Math.random()*100)+1;
            hintLabel.setText("输入你的猜测：");
         }
         else if(e.getSource()==buttonEnter) {
            int guess=0;
            try {  guess=Integer.parseInt(inputGuess.getText());
                   if(guess==number) {
                      hintLabel.setText("猜对了！");
                      long endTime = System.currentTimeMillis();
                    long TotalTime = endTime - startTime;
                      Time.setText("所用时间：" + TotalTime / 1000.0 + "秒");
                      if(TotalTime/1000.0<30) {
                    	  check.setText("你赢了！");
                      }
                      else
                    	  check.setText("你输了！");
                   }
                   else if(guess>number) {
                      hintLabel.setText("猜大了！");
                      inputGuess.setText(null); 
                   }
                   else if(guess<number) {
                       hintLabel.setText("猜小了！");
                       inputGuess.setText(null); 
                   }
               }
             catch(NumberFormatException event) {
                   hintLabel.setText("请输入数字字符");
             } 
         }
    } 
}
